import React, { useState } from "react";
import {
  Table,
  Input,
  Select,
  Button,
  Space,
  Row,
  Col,
  Pagination,
  Modal,
  Form,
} from "antd";
import "./Supplier.scss";
import type { ColumnsType } from "antd/es/table";
import {
  PlusOutlined,
  DeleteOutlined,
  CopyOutlined,
  ExportOutlined,
  ImportOutlined,
  ReloadOutlined,
} from "@ant-design/icons";

const { Option } = Select;

// 定义供应商数据类型
interface SupplierData {
  key: string;
  supplierCode: string;
  supplierName: string;
  industry: string;
  contactPerson: string;
  contactPhone: string;
  email: string;
  status: string;
  address: string;
}

export default function Supplier() {
  // 状态管理
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentEditData, setCurrentEditData] = useState<
    SupplierData | undefined
  >(undefined);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 模拟供应商数据 - 生成100条数据用于测试分页功能
  const generateSupplierData = (): SupplierData[] => {
    const industries = [
      "电子产品",
      "服装制造",
      "食品加工",
      "医药健康",
      "化工原料",
      "机械制造",
      "建筑材料",
      "汽车配件",
      "家具用品",
      "教育培训",
    ];
    const statuses = ["启用", "禁用"];
    const data: SupplierData[] = [];

    for (let i = 1; i <= 100; i++) {
      data.push({
        key: i.toString(),
        supplierCode: `GY${i.toString().padStart(4, "0")}`,
        supplierName: `供应商${i}`,
        industry: industries[(i - 1) % industries.length],
        contactPerson: `联系人${i}`,
        contactPhone: `13800138${i.toString().padStart(3, "0")}`,
        email: `supplier${i}@example.com`,
        status: statuses[Math.floor(Math.random() * 2)],
        address: `${
          [
            "北京市",
            "上海市",
            "广州市",
            "深圳市",
            "杭州市",
            "武汉市",
            "重庆市",
            "成都市",
            "南京市",
            "西安市",
          ][Math.floor(Math.random() * 10)]
        }${
          [
            "朝阳区",
            "浦东新区",
            "天河区",
            "南山区",
            "西湖区",
            "江汉区",
            "渝中区",
            "锦江区",
            "玄武区",
            "雁塔区",
          ][Math.floor(Math.random() * 10)]
        }`,
      });
    }

    return data;
  };

  // 将supplierData改为状态，以便能够更新数据
  const [supplierData] = useState<SupplierData[]>(generateSupplierData());

  // 分页数据
  const paginatedData = supplierData.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  // 定义表格列
  const columns: ColumnsType<SupplierData> = [
    {
      title: "供应商编码",
      dataIndex: "supplierCode",
      key: "supplierCode",
      width: 120,
    },
    {
      title: "供应商名称",
      dataIndex: "supplierName",
      key: "supplierName",
      width: 150,
    },
    {
      title: "所属行业",
      dataIndex: "industry",
      key: "industry",
      width: 100,
    },
    {
      title: "联系人",
      dataIndex: "contactPerson",
      key: "contactPerson",
      width: 80,
    },
    {
      title: "联系电话",
      dataIndex: "contactPhone",
      key: "contactPhone",
      width: 120,
    },
    {
      title: "电子邮箱",
      dataIndex: "email",
      key: "email",
      width: 150,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 60,
      render: (status: string) => (
        <span style={{ color: status === "启用" ? "#52c41a" : "#d9d9d9" }}>
          {status}
        </span>
      ),
    },
    {
      title: "供应商地址",
      dataIndex: "address",
      key: "address",
      width: 180,
    },
    {
      title: "操作",
      key: "action",
      width: 100,
      render: (_, record) => (
        <Space size="middle">
          <a className="edit-link" onClick={() => handleEdit(record)}>
            编辑
          </a>
          <a className="delete-link" onClick={() => handleDelete(record)}>
            删除
          </a>
        </Space>
      ),
    },
  ];

  // 处理编辑操作
  const handleEdit = (record?: SupplierData) => {
    console.log("编辑供应商");
    setIsEdit(true);

    if (record) {
      // 如果直接从表格操作列点击编辑，使用传入的记录
      setCurrentEditData(record);
      setSelectedRowKeys([record.key]); // 同时设置选中行
    } else if (selectedRowKeys.length > 0) {
      // 否则从已选择的行中获取第一条
      const editData = supplierData.find(
        (item) => item.key === selectedRowKeys[0]
      );
      if (editData) {
        setCurrentEditData(editData);
      }
    }

    // 确保有数据后再显示弹窗
    setTimeout(() => {
      setIsModalVisible(true);
    }, 0);
  };

  // 处理删除操作
  const handleDelete = (record?: SupplierData) => {
    return (e?: React.MouseEvent) => {
      e?.preventDefault();
      Modal.confirm({
        title: "确认删除",
        content: "确定要删除选中的供应商吗？",
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          // 这里添加删除逻辑
          console.log("删除供应商", record || selectedRowKeys);
        },
      });
    };
  };

  // 处理新增操作
  const handleAdd = () => {
    console.log("新增供应商");
    setIsEdit(false);
    setCurrentEditData(undefined);
    setIsModalVisible(true);
  };

  // 处理表单提交
  const handleSubmit = (values: SupplierData) => {
    console.log("表单值:", values);

    if (isEdit && currentEditData?.key) {
      // 编辑模式：更新现有数据
      // 实际项目中这里会有更新数据的逻辑
    } else {
      // 新增模式：添加新数据
      // 实际项目中这里会有添加新数据的逻辑
    }

    // 重置状态
    setIsModalVisible(false);
    setIsEdit(false);
    setCurrentEditData(undefined);
  };

  // 创建表单实例
  const [form] = Form.useForm();

  // 当编辑数据变化或弹窗显示状态变化时，更新表单值
  React.useEffect(() => {
    if (isModalVisible) {
      if (currentEditData) {
        // 使用setTimeout确保在Modal完全显示后再设置值
        setTimeout(() => {
          form.setFieldsValue(currentEditData);
        }, 0);
      } else {
        form.resetFields();
      }
    }
  }, [currentEditData, form, isModalVisible]);

  // 处理表单提交
  const handleFormSubmit = () => {
    form
      .validateFields()
      .then((values) => {
        handleSubmit(values as SupplierData);
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });
  };

  // 供应商表单组件 - 用于新增和编辑复用
  const SupplierForm = () => {
    return (
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          status: "启用",
        }}>
        <Form.Item
          label="供应商编码"
          name="supplierCode"
          rules={[{ required: true, message: "请输入供应商编码" }]}>
          <Input placeholder="请输入供应商编码" disabled={isEdit} />
        </Form.Item>

        <Form.Item
          label="供应商名称"
          name="supplierName"
          rules={[{ required: true, message: "请输入供应商名称" }]}>
          <Input placeholder="请输入供应商名称" />
        </Form.Item>

        <Form.Item
          label="所属行业"
          name="industry"
          rules={[{ required: true, message: "请选择所属行业" }]}>
          <Select placeholder="请选择所属行业">
            <Option value="电子产品">电子产品</Option>
            <Option value="服装制造">服装制造</Option>
            <Option value="食品加工">食品加工</Option>
            <Option value="医药健康">医药健康</Option>
            <Option value="化工原料">化工原料</Option>
            <Option value="机械制造">机械制造</Option>
            <Option value="建筑材料">建筑材料</Option>
            <Option value="汽车配件">汽车配件</Option>
            <Option value="家具用品">家具用品</Option>
            <Option value="教育培训">教育培训</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="联系人"
          name="contactPerson"
          rules={[{ required: true, message: "请输入联系人" }]}>
          <Input placeholder="请输入联系人" />
        </Form.Item>

        <Form.Item
          label="联系电话"
          name="contactPhone"
          rules={[
            { required: true, message: "请输入联系电话" },
            { pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号码" },
          ]}>
          <Input placeholder="请输入联系电话" />
        </Form.Item>

        <Form.Item
          label="电子邮箱"
          name="email"
          rules={[
            { required: true, message: "请输入电子邮箱" },
            { type: "email", message: "请输入正确的电子邮箱" },
          ]}>
          <Input placeholder="请输入电子邮箱" />
        </Form.Item>

        <Form.Item
          label="状态"
          name="status"
          rules={[{ required: true, message: "请选择状态" }]}>
          <Select placeholder="请选择状态">
            <Option value="启用">启用</Option>
            <Option value="禁用">禁用</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="供应商地址"
          name="address"
          rules={[{ required: true, message: "请输入供应商地址" }]}>
          <Input.TextArea rows={2} placeholder="请输入供应商地址" />
        </Form.Item>
      </Form>
    );
  };

  return (
    <div className="supplier-management">
      <div className="supplier-content">
        {/* 搜索筛选区域 */}
        <div className="search-filter">
          <Row gutter={16} align="middle">
            <Col span={5}>
              <Input placeholder="请输入供应商名称/编码" />
            </Col>
            <Col>
              <Select placeholder="请选择状态">
                <Option value="启用">启用</Option>
                <Option value="禁用">禁用</Option>
              </Select>
            </Col>
            <Col>
              <Select placeholder="所属行业">
                <Option value="电子产品">电子产品</Option>
                <Option value="服装制造">服装制造</Option>
                <Option value="食品加工">食品加工</Option>
                <Option value="其他">其他</Option>
              </Select>
            </Col>
            <Col span={5}>
              <Input placeholder="联系人" />
            </Col>
            <Col span={4}>
              <Space>
                <Button className="reset-button">重置</Button>
                <Button type="primary" className="search-button">
                  查询
                </Button>
                <Button className="advanced-search-button">高级搜索</Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 操作按钮区域 */}
        <div className="action-buttons">
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRowKeys.length === 0}
              onClick={handleDelete()}>
              删除
            </Button>
            <Button icon={<CopyOutlined />}>复制</Button>
            <Button icon={<ExportOutlined />}>导出</Button>
            <Button icon={<ImportOutlined />}>导入</Button>
            <Button icon={<ReloadOutlined />}>刷新</Button>
          </Space>
        </div>

        {/* 供应商列表表格 */}
        <div className="supplier-table">
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={paginatedData}
            pagination={false}
            scroll={{
              x: "max-content",
              y: 400, // 设置表格内容区域的高度，超出时显示垂直滚动条
            }}
          />
        </div>

        {/* 分页区域 */}
        <div className="pagination">
          <div className="total-count">总 100 条</div>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={supplierData.length}
            onChange={(page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `总 ${total} 条`}
            pageSizeOptions={["10", "20", "50", "100"]}
          />
        </div>
      </div>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={isEdit ? "编辑供应商" : "新增供应商"}
        open={isModalVisible}
        onOk={handleFormSubmit}
        onCancel={() => setIsModalVisible(false)}
        okText="确定"
        cancelText="取消"
        width={600}>
        <SupplierForm />
      </Modal>
    </div>
  );
}
